// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;

namespace SnapObjects.Data.Odbc
{
    public class OdbcHanaStringTypeMapping : OdbcStringTypeMapping, IOdbcHanaTypeMapping
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="OdbcStringTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="DbType" /> to be used. </param>
        /// <param name="unicode"> A value indicating whether the type should handle Unicode data or not. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        public OdbcHanaStringTypeMapping(
            [NotNull] string dbTypeName,
            [CanBeNull] DbType? dbType,
            bool unicode = false,
            int? size = null)
            : base(dbTypeName, dbType, unicode, size)
        {
            _maxSpecificSize = CalculateSize(unicode, size);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new OdbcAseStringTypeMapping(
                           dbTypeName,
                           this.DbType,
                           this.IsUnicode,
                           size);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            // For strings and byte arrays, set the max length to the size facet if specified, or
            // 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
            // fragmentation by setting lots of different Size values otherwise always set to
            // -1 (unbounded) to avoid SQL client size inference.

            var value = parameter.Value;

            var length = (value as string)?.Length ?? (value as byte[])?.Length;

            if (parameter.Direction == ParameterDirection.Output ||
                parameter.Direction == ParameterDirection.InputOutput)
            {
                parameter.Size = _maxSpecificSize;
            }
            else
            {
                if (value == null || value == DBNull.Value)
                {
                    parameter.Size = -1;
                }
                else
                {
                    parameter.Size = length.Value < _maxSpecificSize
                        ? length.Value : -1;
                }
            }    
        }
        
        private static int CalculateSize(bool unicode, int? size)
            => unicode
                ? size.HasValue && size < 4000 ? size.Value : 4000
                : size.HasValue && size < 8000 ? size.Value : 8000;
                
        public string ReBuildDbTypeName(DbParameter parameter)
        {
            if (parameter.Size > 0)
            {
                return this.DbTypeName + "(" + parameter.Size + ")";
            }

            return this.DbTypeName + "(1)";
        }
    }
}
